package org.jsola.hr.web;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.jsola.core.Page;
import org.jsola.core.Result;
import org.jsola.exception.ParamException;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dto.SalaryTableAddDTO;
import org.jsola.hr.dto.SalaryTableUpdateDTO;
import org.jsola.hr.query.SalaryTableExportQuery;
import org.jsola.hr.query.SalaryTableQuery;
import org.jsola.hr.service.ISalaryTableService;
import org.jsola.hr.vo.SalaryTableListVO;
import org.jsola.hr.vo.SalaryTableVO;
import org.jsola.user.core.TokenUser;
import org.jsola.user.core.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;


/**
 * 工资表（工资条统计）
 *
 * @author zhr
 */
@RestController("hrSalaryTableController")
@RequestMapping(HrConstants.API_PATH + "/v1/salaryTables")
public class SalaryTableController implements ISalaryTableControllerAPI {

    @Autowired
    private ISalaryTableService salaryTableService;

    @Override
    @PostMapping
    public Result<SalaryTableVO> save(@Valid @RequestBody SalaryTableAddDTO salaryTableAddDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 新增工资表（工资条统计）权限校验

        return Result.success(
                salaryTableService.save(salaryTableAddDTO, tokenUser)
        );
    }


    @Override
    @PutMapping
    public Result<Integer> update(@Valid @RequestBody SalaryTableUpdateDTO salaryTableUpdateDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 修改工资表（工资条统计）权限校验

        int count = salaryTableService.update(salaryTableUpdateDTO, tokenUser);
        if (count == 0) {
            throw new ParamException("更新失败，请刷新页面后重试");
        }
        return Result.success(count);
    }



    @Override
    @DeleteMapping(value = "/{salaryTableId}")
    public Result<Integer> delete(@PathVariable String salaryTableId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 彻底删除工资表（工资条统计）权限校验

        int count = salaryTableService.deleteByIds(tokenUser, salaryTableId);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @DeleteMapping
    public Result<Integer> deleteBatch(@RequestBody String[] salaryTableIds) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 批量彻底删除工资表（工资条统计）权限校验

        int count = salaryTableService.deleteByIds(tokenUser, salaryTableIds);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @GetMapping(value = "/{salaryTableId}")
    public Result<SalaryTableVO> findById(@PathVariable String salaryTableId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看工资表（工资条统计）权限校验

        return Result.success(
            salaryTableService.selectById(salaryTableId, tokenUser.getSiteId())
        );
    }

    @Override
    @GetMapping(value = "/listAll")
    public Result<List<SalaryTableListVO>> listAll(@Valid SalaryTableQuery salaryTableQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看工资表（工资条统计）权限校验

        return Result.success(
            salaryTableService.select(salaryTableQuery, tokenUser.getSiteId())
        );
    }


    @Override
    @GetMapping
    public Result<Page<SalaryTableListVO>> page(@Valid SalaryTableQuery salaryTableQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
            salaryTableService.selectPage(salaryTableQuery, tokenUser.getSiteId())
        );
    }

    @Override
    @GetMapping(value = "/listAllRelation")
    public Result<Map<String, List<SalaryTableListVO>>> listAllRelation(@Valid SalaryTableQuery salaryTableQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看工资表（工资条统计）权限校验
        if(StringUtils.isBlank(salaryTableQuery.getYear())){
            throw new ParamException("年份参数不可为空");
        }

        return Result.success(
                salaryTableService.listAllRelation(salaryTableQuery, tokenUser.getSiteId())
        );
    }

    @Override
    @GetMapping(value = "/salaryTableImportedYearList")
    public Result<List<String>> salaryTableImportedYearList(@Valid SalaryTableQuery salaryTableQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看工资表（工资条统计）权限校验

        return Result.success(
                salaryTableService.salaryTableImportedYearList(salaryTableQuery, tokenUser.getSiteId())
        );
    }

    @Override
    @GetMapping(value = "/salaryTableGroupByEmpId")
    public Result<List<SalaryTableListVO>> salaryTableGroupByEmpId(@Valid SalaryTableQuery salaryTableQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看工资表（工资条统计）权限校验
        if(StringUtils.isBlank(salaryTableQuery.getYear())){
            throw new ParamException("年份参数不可为空");
        }

        return Result.success(
                salaryTableService.salaryTableGroupByEmpId(salaryTableQuery, tokenUser.getSiteId())
        );
    }

    @Override
    @GetMapping(value = "/salaryTableGroupByMonthEmpId")
    public Result<List<SalaryTableListVO>> salaryTableGroupByMonthEmpId(@Valid SalaryTableQuery salaryTableQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看工资表（工资条统计）权限校验
        if(StringUtils.isBlank(salaryTableQuery.getYear())){
            throw new ParamException("年份参数不可为空");
        }
        if(StringUtils.isBlank(salaryTableQuery.getMonth())){
            throw new ParamException("月份参数不可为空");
        }

        return Result.success(
                salaryTableService.salaryTableGroupByMonthEmpId(salaryTableQuery, tokenUser.getSiteId())
        );
    }

    @Override
    @PostMapping(value = "/export")
    public ResponseEntity<Resource> salaryTableExport(@Valid @RequestBody SalaryTableExportQuery salaryTableExportQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看工资表（工资条统计）权限校验
        String excelFilePath = salaryTableService.salaryTableExport(salaryTableExportQuery,tokenUser.getSiteId());
        // 编码文件名，防止乱码
        String filenames = new String(FilenameUtils.getName(excelFilePath).getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=\"" + filenames + "\"")
                .header(HttpHeaders.CONTENT_TYPE,"application/vnd.ms-excel")
                .body(new FileSystemResource(excelFilePath));
    }

}

